package top.lyjwn.ajui.widget.text;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xuexiang.xui.widget.textview.autofit.AutoFitTextView;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import top.lyjwn.ajui.R;
import top.lyjwn.ajui.listener.OnCallBackListener;

/**
 * 带标签的输入框
 *
 * @author luoyujie
 */
public class TagEditText extends FrameLayout {


    /**
     * 提示文字
     */
    private String hint;
    /**
     * 错误提示
     */
    private String hintError;

    /**
     * 提示文字的颜色
     */
    private int hintColor;

    /**
     * 是否可以点击
     */
    private boolean focusable = true;

    /**
     * 内容最大长度
     */
    private int maxLength = -1;


    /**
     * 提示的容器
     */
    private LinearLayout tv_content_hint_container;

    /**
     * 提示
     */
    private AutoFitTextView tv_content_hint;

    /**
     * 错误提示
     */
    private AutoFitTextView tv_content_hint_error;

    /**
     * 内容
     */
    private EditText tag_edit_text_et_content;

    private OnVerify onVerify;

    private OnVerifyListener onVerifyListener;

    public TagEditText(Context context) {
        super(context);
        init(context);
    }

    public TagEditText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TagEditText);
        String tagEditText_hint = ta.getString(R.styleable.TagEditText_TagEditText_hint);
        hint = tagEditText_hint;
        boolean tagEditText_focusable = ta.getBoolean(R.styleable.TagEditText_TagEditText_focusable, true);
        focusable = tagEditText_focusable;
        int tagEditText_maxLength = ta.getInteger(R.styleable.TagEditText_TagEditText_maxLength, -1);
        maxLength = tagEditText_maxLength;
        int tagEditText_hintColor = ta.getColor(R.styleable.TagEditText_TagEditText_hintColor, Color.parseColor("#999999"));
        hintColor = tagEditText_hintColor;
        String tagEditText_hintError = ta.getString(R.styleable.TagEditText_TagEditText_hintError);
        hintError = tagEditText_hintError == null ? "" : tagEditText_hintError;
        init(context);
    }

    private void init(Context context) {
        View v = LayoutInflater.from(context).inflate(R.layout.widget_tag_edit_text, this);
        tv_content_hint_container = v.findViewById(R.id.tag_edit_text_tv_content_hint_container);
        tv_content_hint_error = v.findViewById(R.id.tag_edit_text_tv_content_hint_error);
        String hint1 = hint + "   " + hintError;
        SpannableString msp = new SpannableString(hint1);
        msp.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new ForegroundColorSpan(Color.parseColor("#F83A3A")), hint1.length()-hintError.length(), hint1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_content_hint_error.setText(msp);
        tv_content_hint = v.findViewById(R.id.tag_edit_text_tv_content_hint);
        tv_content_hint.setTextColor(hintColor);
        tag_edit_text_et_content = v.findViewById(R.id.tag_edit_text_et_content);
        tv_content_hint.setText(hint);
        setFocusable(focusable);
        if (maxLength > -1) {
            setMaxLength(maxLength);
        }
        tv_content_hint_container.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                animationUp(new OnCallBackListener() {
                    @Override
                    public void finish(boolean is, Object o) {
                        tag_edit_text_et_content.requestFocus();
                    }
                });
            }
        });
        tag_edit_text_et_content.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus && TextUtils.isEmpty(tag_edit_text_et_content.getText().toString())) {
                    animationDown();
                }
                if (hasFocus) {
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(tag_edit_text_et_content, 0);
                }
            }
        });

        tag_edit_text_et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //检测数据
                if (onVerify != null) {
                    boolean result = onVerify.run(TagEditText.this, getText());
                    if (onVerifyListener != null) {
                        onVerifyListener.result(TagEditText.this, result);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 写入提示的颜色
     *
     * @param color
     */
    public void setHintColor(@ColorInt int color) {
        tv_content_hint.setTextColor(color);
    }

    /**
     * 写入错误提示
     *
     * @param text
     */
    public void setHintError(String text) {
        tv_content_hint_error.setText(text);
    }

    /**
     * 显示错误提示
     */
    public void showHintError() {
        tv_content_hint.setVisibility(GONE);
        tv_content_hint_error.setVisibility(VISIBLE);
    }

    /**
     * 隐藏错误提示
     */
    public void hideHintError() {
        tv_content_hint.setVisibility(VISIBLE);
        tv_content_hint_error.setVisibility(GONE);
    }


    /**
     * 获得提示文字
     *
     * @return
     */
    public String getHint() {
        return hint;
    }

    /**
     * 写入提示文字
     *
     * @param hint
     */
    public void setHint(String hint) {
        tv_content_hint.setText(hint);
        this.hint = hint;
    }

    /**
     * 获得内容文字
     *
     * @return
     */
    public String getText() {
        return tag_edit_text_et_content.getText().toString();
    }

    /**
     * 写入内容文字
     *
     * @return
     */
    public void setText(String text) {
        tag_edit_text_et_content.setText(text);
        if (text != null && text.length() > 0) {
            animationUp(new OnCallBackListener() {
                @Override
                public void finish(boolean is, Object o) {

                }
            });
        }
    }

    /**
     * 是否可获得输入焦点
     *
     * @param focusable
     */
    public void setFocusable(boolean focusable) {
        tag_edit_text_et_content.setFocusable(focusable);
    }

    /**
     * 检验数据是否满足检验要求
     *
     * @return 是否满足检验要求
     */
    public boolean verify() {
        boolean run = onVerify.run(this, tag_edit_text_et_content.getText().toString());
        onVerifyListener.result(this, run);
        return run;
    }


    /**
     * 触发点击事件
     * @return
     */
    public boolean callOnClick() {
        return tv_content_hint.callOnClick();
    }

    /**
     * 写入光标位置
     * @param length
     */
    public void setSelection(int length) {
        tag_edit_text_et_content.setSelection(length);
    }

    /**
     * 写入内存最大长度限制
     *
     * @param length
     */
    public void setMaxLength(int length) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                if (dest.length() + source.length() <= length) {
                    return source;
                } else {
                    return "";
                }

            }
        };
        tag_edit_text_et_content.setFilters(new InputFilter[]{filter});
    }

    public void setTextWatcher(TextWatcher watcher) {
        tag_edit_text_et_content.addTextChangedListener(watcher);
    }

    public void setInputType(int type) {
        tag_edit_text_et_content.setInputType(type);
    }

    /**
     * 缩小标签动画
     */
    private void animationUp(OnCallBackListener l) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(tv_content_hint_container, "scaleX", 0.6f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(tv_content_hint_container, "scaleY", 0.6f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(100);
        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.play(scaleX).with(scaleY); //两个动画同时开始
        animatorSet.start();

        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tag_edit_text_et_content.setVisibility(View.VISIBLE);
                l.success(animation);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    /**
     * 复原动画
     */
    private void animationDown() {
        tag_edit_text_et_content.setVisibility(View.GONE);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(tv_content_hint_container, "scaleX", 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(tv_content_hint_container, "scaleY", 1);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(100);
        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.play(scaleX).with(scaleY); //两个动画同时开始
        animatorSet.start();
    }

    public void setTextSize(float size) {
        tag_edit_text_et_content.setTextSize(size);
    }

    public void setTextChangedListener(TextChangedListener p_textChangedListener, String p_hint) {
        tag_edit_text_et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                p_textChangedListener.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_content_hint.setText(tag_edit_text_et_content.getText().toString().length() > 0 ? p_hint : hint);
                p_textChangedListener.onTextChanged(s, start, before, count);

            }

            @Override
            public void afterTextChanged(Editable s) {
                p_textChangedListener.afterTextChanged(s);
            }
        });

    }

    public void setOnVerify(OnVerify onVerify) {
        this.onVerify = onVerify;
    }

    public void setOnVerifyListener(OnVerifyListener onVerifyListener) {
        this.onVerifyListener = onVerifyListener;
    }

    public void setTextChangedListener(TextChangedListener textChangedListener) {
        setTextChangedListener(textChangedListener, hint);
    }

    public void setTextChangedHint(String p_hint) {
        setTextChangedListener(new TextChangedListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        }, p_hint);
    }


    @Override
    public void setOnClickListener(OnClickListener l) {
        OnClickListener onClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tag_edit_text_et_content.isFocusable()) {
                    InputMethodManager imm = (InputMethodManager) getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
//                        imm.hideSoftInputFromWindow(tv_content_hint.getWindowToken(), 0);
                        imm.hideSoftInputFromWindow(tag_edit_text_et_content.getWindowToken(), 0);
                    }
                }
                l.onClick(v);
            }
        };
        tv_content_hint_container.setOnClickListener(onClickListener);
        tag_edit_text_et_content.setOnClickListener(onClickListener);
    }

    /**
     * 输入框改变接口
     */
    public interface TextChangedListener {


        void beforeTextChanged(CharSequence s, int start, int count, int after);

        void onTextChanged(CharSequence s, int start, int before, int count);

        void afterTextChanged(Editable s);

    }

    /**
     * 校验内容
     */
    public interface OnVerify {
        boolean run(TagEditText tagEditText, String content);
    }

    /**
     * 校验结果
     */
    public interface OnVerifyListener {
        void result(TagEditText tagEditText, boolean isCorrect);
    }
}
